package com.lyl.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.alicloud.sms.ISmsService;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyl.domain.Sms;
import com.lyl.mapper.SmsMapper;
import com.lyl.service.ConfigService;
import com.lyl.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author lylbell
 * @date 2021-06-30 13:07
 */
@Service
@Slf4j
public class SmsServiceImpl extends ServiceImpl<SmsMapper, Sms> implements SmsService {


    @Autowired
   private ISmsService smsService;

    @Autowired
    private ConfigService configService;


    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    /**
     * 发送短信
     *
     * @param sms
     * @return
     */
    @Override
    public Boolean sendMessage(Sms sms) {
        log.info("发送短信{}", JSON.toJSONString(sms,true));
        SendSmsRequest request = buildSmsRequest(sms);
        try {
            SendSmsResponse sendSmsResponse = smsService.sendSmsRequest(request); //发送短信
            String code = sendSmsResponse.getCode();
            if ("OK".equals(code)) {  //判断短信是否发送成功
                sms.setStatus(1);
                return save(sms);
            }else {
                return false;
            }

        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 创建发送的短信信息
     * @param sms
     * @return
     */
    private SendSmsRequest buildSmsRequest(Sms sms) {
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(sms.getMobile());
        //1.动态获取签名和模板代码
//        Config signConfig = configService.getConfigByCode("SIGN");
        request.setSignName("Coin货币商城");//设置签名
        request.setTemplateCode("SMS_218568579");

        //2.获取随机短信验证码
        String code = RandomUtil.randomNumbers(6);

        //3.将短信验证码存到redis当中SMS:VERIFY_OLD_PHOME:电话号码
        redisTemplate.opsForValue().set("SMS"+sms.getTemplateCode()+":"+sms.getMobile(),code,5, TimeUnit.MINUTES);
        request.setTemplateParam("{\"code:\"" + code + "\"}");
        //4.给sms中的值赋值。

        return request;
    }
}
